package com.qf.qfusermanager.config;

import com.alibaba.fastjson.JSON;
import com.qf.common.bean.R;
import com.qf.qfusermanager.filter.JwtVerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authManager() throws Exception {
        return authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //放开跨站伪造认证
        http.csrf().disable();
        //跨域设置（不需要-网关层已经实现）
        //设置哪些资源需要认证，哪些资源需要权限
        http.authorizeRequests()
                .antMatchers("/user/auth/doLogin").permitAll()
                .antMatchers("/user/cmd/send").permitAll()
                .antMatchers("/user/**").authenticated();


        http.exceptionHandling()
                //当访问资源需要登录，但是没有登录时，会触发回调
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        R r = R.fail(R.Code.UNAUTHENTICATED,"尚未登录");
                        String json = JSON.toJSONString(r);

                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(json);
                    }
                })
                //当访问资源需要权限，但是没有权限时，会触发回调
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        R r = R.fail(R.Code.NO_AUTH,"无权访问");
                        String json = JSON.toJSONString(r);

                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(json);
                    }
                });

        //添加一个对jwt进行认证的过滤器
        http.addFilter(new JwtVerifyFilter(authenticationManager()));
    }
}
